package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.enums.PaymentStatus;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.mapper.OrderInfoMapper;
import com.atguigu.gmall.payment.mapper.PaymentInfoMapper;
import com.atguigu.gmall.payment.service.PaymentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Service
public class PaymentServiceImpl implements PaymentService {
    @Autowired
    private PaymentInfoMapper paymentInfoMapper;
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private RabbitService rabbitService;

    //生成财务系统需要的"支付表" 和钱相关的表
    @Override
    public PaymentInfo insert(Long orderId, PaymentType paymentType) {
        //1.先查询是否已经生成了支付表(防止重复保存支付表) 幂等性问题
        PaymentInfo paymentInfo = paymentInfoMapper.selectOne(new QueryWrapper<PaymentInfo>().eq("order_id", orderId));
        if (null != paymentInfo) {
            //1.1已经生成支付表 更新支付方式
            paymentInfo.setPaymentType(paymentType.name());
            paymentInfoMapper.updateById(paymentInfo);
        } else {
            //1.2未生成支付表 生成
            paymentInfo = new PaymentInfo();
            OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
            paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
            paymentInfo.setOrderId(orderInfo.getId());
            paymentInfo.setPaymentType(paymentType.name());
            paymentInfo.setTotalAmount(orderInfo.getTotalAmount());
            //标题是订单详情
            paymentInfo.setSubject(orderInfo.getTradeBody());
            //支付中
            paymentInfo.setPaymentStatus(PaymentStatus.UNPAID.name());
            paymentInfo.setCreateTime(new Date());
            paymentInfoMapper.insert(paymentInfo);
        }
        return paymentInfo;
    }

    //查询支付表
    @Override
    public PaymentInfo selectPayment(String outTradeNo) {
        return paymentInfoMapper.selectOne(new QueryWrapper<PaymentInfo>().
                eq("out_trade_no", outTradeNo));
    }

    //支付成功后 更新支付表
    //out_trade_no是支付前的交易号
    //trade_no是支付后生成的流水号
    @Override
    public void updatePaymentInfo(Map<String, String> paramMap) {
        //1.注意幂等性问题 更新支付表 先查询,必须不为空且未支付才更新
        PaymentInfo paymentInfo = selectPayment(paramMap.get("out_trade_no"));
        if (null != paymentInfo && PaymentStatus.UNPAID.name().equals(paymentInfo.getPaymentStatus())) {
            //2.更新支付表
            //2.1 设置为已支付
            paymentInfo.setPaymentStatus(PaymentStatus.PAID.name());
            //2.2 银行流水
            paymentInfo.setTradeNo(paramMap.get("trade_no"));
            //2.3 回调时间
            try {
                paymentInfo.setCallbackTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").
                        parse(paramMap.get("notify_time")));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //2.4 回调内容
            paymentInfo.setCallbackContent(JSONObject.toJSONString(paramMap));
            //更新
            paymentInfoMapper.updateById(paymentInfo);
            //3.发消息给MQ 让MQ通知订单 更新订单状态
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_PAYMENT_PAY,
                    MqConst.ROUTING_PAYMENT_PAY, paymentInfo.getOrderId());
        }
    }
}

